<template>
  <div class="content">
    <div class="scroll-view-box" v-loading="submitBtn">
      <div class="user-title-box">基础信息</div>
      <el-form label-width="120px" :inline="true" :model="addForm" :rules="addRules" ref="addRules"
        label-position="top">
        <el-form-item label="采购合同" prop="contract_id">
          <el-select filterable @change="contractSelectFunc" v-model="addForm.contract_id" placeholder="选择采购合同" clearable
            class="input-width">
            <el-option v-for="item in contractList" :key="item.Id" :label="item.contract_name" :value="item.Id">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="报价单状态" prop="state" v-if="addForm.Id">
          <el-radio-group v-model="addForm.state">
            <el-radio :label="1">生效</el-radio>
            <el-radio :label="2">失效</el-radio>
          </el-radio-group>
        </el-form-item>
        <div class="user-title-box">产品规格</div>
        <div class="size-box" v-for="(item, index) in addForm.specs_arr" :key="index">
          <p class="size-box-title">产品{{ index + 1 }}
            <span class="del-btn" @click="delSpecsFunc(index)">删除</span>
          </p>
          <div class="size-box-content">
            <el-form-item label="产品规格" :prop="'specs_arr.' + index + '.product_specs_id'" :rules="[
              { required: true, message: '请输入产品规格', trigger: 'change' },
            ]">
              <el-select filterable @change="productSpecsChange" v-model="item.product_specs_id" placeholder="选择产品规格" clearable
                class="input-width">
                <el-option v-for="item in productSpecsList" :key="item.Id" :label="item.product_specs_name"
                  :value="item.Id" :disabled="item.disabled">
                </el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="单价(不含税)" :prop="'specs_arr.' + index + '.unit_price'" :rules="[
              { required: true, message: '请输入单价(不含税)', trigger: 'change' },
            ]">
              <el-input @change="jsPriceTaxFunc(index)" v-input-limit="2" v-model="item.unit_price"
                placeholder="输入单价(不含税)" clearable class="input-width">
                <template slot="suffix">元</template></el-input>
            </el-form-item>
            <el-form-item label="税率" :prop="'specs_arr.' + index + '.tax_rate'" :rules="[
              { required: true, message: '请输入税率', trigger: 'change' },
            ]">
              <el-input v-input-limit="2" @change="jsPriceTaxFunc(index)" v-model="item.tax_rate" placeholder="输入税率"
                clearable class="input-width">
                <template slot="suffix">%</template></el-input>
            </el-form-item>
            <el-form-item label="单价(含税)" :prop="'specs_arr.' + index + '.unit_price_tax'" :rules="[
              { required: true, message: '请输入单价(含税)', trigger: 'change' },
            ]">
              <el-input readonly v-model="item.unit_price_tax" placeholder="输入单价(含税)" clearable class="input-width">
                <template slot="suffix">元</template></el-input>
            </el-form-item>
          </div>
        </div>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button type="primary" @click="addSpecsFunc" :loading="submitBtn">新增产品规格</el-button>
        <el-button type="primary" @click="saveSubmit('addRules')" :loading="submitBtn">提交</el-button>
        <el-button @click="cancelFunc">关闭</el-button>
      </span>
    </div>
  </div>
</template>
<script>
import purchaseApi from "@/api/purchaseApi";
import * as math from "mathjs";
export default {
  name: 'addQuotation',
  data() {
    return {
      value: 1,
      addForm: {
        contract_id: "",
        state: 1,
        specs_arr: [{
          product_specs_id: '',
          unit_price: '',
          unit_price_tax: '',
          tax_rate: '',
        }]
      },
      addRules: {
        contract_id: [
          {
            required: true,
            message: "请选择关联合同",
            trigger: "change",
          },
        ],
        state: [
          {
            required: true,
            message: "请选择报价单状态",
            trigger: "change",
          },
        ],
      },
      submitBtn: false,
      contractList: [],//合同列表
      productSpecsList: [],//产品规格
    };
  },
  computed: {
    hisList() {
      return this.$store.getters.routerHis;
    },
    path() {
      return this.$route.path;
    },
  },
  mounted() {
    this.getContract();//合同列表
    this.getProductSpecs(() => {
      this.getQuotationInfo();//报价单详情
    });//产品规格

  },
  methods: {
    // 产品规格筛选(已选禁用，不能重复选择)
    productSpecsChange() {
      let specs_arr = this.addForm.specs_arr;
      let productSpecsList = this.productSpecsList;
      let product_specs_id_arr = [];
      specs_arr.forEach(item => {
        product_specs_id_arr.push(item.product_specs_id);
      })
      productSpecsList.forEach(item => {
        let index = product_specs_id_arr.findIndex(child => {
          return item.Id == child
        })
        if (index != -1) {
          item.disabled = true;
        } else {
          item.disabled = false;
        }
      })
      this.productSpecsList = productSpecsList;
    },
    // 选择合同获取供应商id
    contractSelectFunc() {
      if (!this.addForm.contract_id) return;
      let contractList = this.contractList;
      let index = contractList.findIndex(item => {
        return item.Id == this.addForm.contract_id;
      })
      if (index == -1) return;
      this.addForm.supplier_id = contractList[index].supplier_id;
    },
    // 计算单价含税
    jsPriceTaxFunc(index) {
      let addForm = this.addForm;
      if (addForm.specs_arr[index].unit_price && addForm.specs_arr[index].tax_rate) {
        //1+税率
        let tax_rateOld = math.format(
          math.divide(
            math.bignumber(addForm.specs_arr[index].tax_rate),
            math.bignumber(100)
          )
        );
        console.log(addForm.specs_arr[index].tax_rate, '税率')
        let tax_rate = math.format(
          math.add(
            math.bignumber(1),
            math.bignumber(Number(tax_rateOld))
          )
        );
        // 计算税后单价
        console.log(tax_rate, "shuilv", addForm.specs_arr[index].unit_price)
        let unit_price_tax = math.format(
          math.multiply(
            math.bignumber(Number(tax_rate)),
            math.bignumber(addForm.specs_arr[index].unit_price)
          )
        )
        this.addForm.specs_arr[index].unit_price_tax = Number(unit_price_tax).toFixed(2);
      }
    },
    // 报价单详情
    getQuotationInfo() {
      if (!this.$route.query.id) return;
      purchaseApi.getQuotationInfo({
        quotation_id: this.$route.query.id
      }).then(res => {
        console.log(res, "报价单详情")
        if (res.code == 200) {
          res.data.quotation_id = res.data.Id;
          res.data.specs_arr = [];
          res.data.specs_list.forEach(item => {
            item.tax_rate = Number(item.tax_rate);
            item.unit_price = Number(item.unit_price);
            item.unit_price_tax = Number(item.unit_price_tax);
            res.data.specs_arr.push({
              product_specs_id: item.product_specs_id,
              unit_price: item.unit_price,
              unit_price_tax: item.unit_price_tax,
              tax_rate: item.tax_rate,
            })
          })
          // res.data.specs_arr = res.data.specs_list;
          this.addForm = res.data;
          this.$nextTick(() => {
            this.productSpecsChange();
          })
        }
      })
    },
    // 产品规格
    getProductSpecs(cb) {
      purchaseApi.getProductSpecs({
        page: 1,
        num: 999
      }).then(res => {
        console.log(res, "产品规格")
        if (res.code == 200) {
          this.productSpecsList = res.data.list;
          cb && cb();
        }
      })
    },
    // 合同列表
    getContract() {
      purchaseApi.getContract({
        page: 1,
        num: 999
      }).then(res => {
        console.log(res, "合同列表")
        if (res.code == 200) {
          this.contractList = res.data.list;
        }
      })
    },
    // 删除产品规格
    delSpecsFunc(index) {
      if (this.addForm.specs_arr.length == 1) {
        this.$message({
          type: 'warning',
          message: "至少需要有一项产品规格"
        })
        return;
      }
      this.addForm.specs_arr.splice(index, 1);
    },
    // 添加产品规格
    addSpecsFunc() {
      this.addForm.specs_arr.push({
        product_specs_id: '',
        unit_price: '',
        unit_price_tax: '',
        tax_rate: '',
      })
    },
    // 提交
    saveSubmit(formName) {
      let addForm = JSON.parse(JSON.stringify(this.addForm));
      console.log(addForm)
      this.$refs[formName].validate((valid) => {
        if (valid) {
          if (addForm.Id) {
            addForm.quotation_id = addForm.Id;
            this.updateQuotation(addForm);
            return;
          }
          // addForm.specs_arr = JSON.stringify(addForm.specs_arr);
          this.addQuotation(addForm);
        } else {
          return false;
        }
      });
    },
    // 添加报价单
    addQuotation(obj) {
      this.submitBtn = true;
      purchaseApi.addQuotation(obj).then(res => {
        console.log(res, "添加报价单")
        this.submitBtn = false;
        if (res.code == 200) {
          this.cancelFunc();
        }
        this.$message({
          type: res.code == 200 ? 'success' : 'warning',
          message: res.message
        })
      })
    },
    // 更新报价单
    updateQuotation(obj) {
      this.submitBtn = true;
      purchaseApi.updateQuotation(obj).then(res => {
        console.log(res, "更新报价单")
        this.submitBtn = false;
        if (res.code == 200) {
          this.cancelFunc();
        }
        this.$message({
          type: res.code == 200 ? 'success' : 'warning',
          message: res.message
        })
      })
    },
    // 取消
    cancelFunc() {
      this.$goBackTab(this);
    },
  },
};
</script>
<style lang="scss" scoped>
@import "./index.scss";
@import "@/styles/addPage.scss";
</style>